<template>
  <div>
    <!-- 工具栏容器 -->
    <div :id="toolbarId"></div>
    <!-- 编辑器容器 -->
    <div :id="editorId"></div>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import CKEditor from "@ckeditor/ckeditor5-build-decoupled-document";
import "@ckeditor/ckeditor5-build-decoupled-document/build/translations/zh-cn";
import axios from "axios";

export default {
  props: {
    value: {
      type: String,
      default: "",
    },
    readOnly: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      toolbarId: "toolbar-container", //工具栏Id
      editorId: "editor", //编辑器Id
      editor: null, //编辑器实例
    };
  },
  created() {
    //Id随机化，避免多个相同组件的Id冲突
    this.toolbarId += this.randomId;
    this.editorId += this.randomId;
  },
  mounted() {
    this.initCKEditor();
  },
  computed: {
    ...mapGetters(["root","token"]),
    //随机数
    randomId() {
      var Num = "";
      for (var i = 0; i < 6; i++) {
        Num += Math.floor(Math.random() * 10);
      }
      return Num;
    },
  },
  methods: {
    initCKEditor() {
      class UploadAdapter {
        constructor(loader) {
          this.loader = loader;
        }
        upload() {
          return new Promise((resolve, reject) => {
            const data = new FormData();
            this.loader.file.then((realFile) => {
              data.append("file", realFile, realFile.name);
              let config = {
                headers: {
                  "Content-Type": "multipart/form-data",
                  Authorization:
                    "Bearer " + this.token,
                },
              };
              axios
                .post(this.root + "adminApi/Utility/Editor_Upload", data, config)
                .then((res) => {
                  if (res.status === 200) {
                    const url =
                      this.root +
                      `adminApi/Utility/PreviewPic?VirtualPath=` +
                      res.data.data;
                    resolve({
                      default: url,
                    });
                  } else {
                    reject("");
                  }
                });
            });
          });
        }
        abort() {}
      }
      CKEditor.create(document.querySelector("#" + this.editorId), {
        language: "zh-cn",
        ckfinder: {
          //uploadUrl: this.root + "adminApi/Utility/Editor_Upload"
          //后端处理上传逻辑返回json数据,包括uploaded(选项true/false)和url两个字段
        },
      })
        .then((editor) => {
          //初始化编辑器内容
          editor.setData(this.value ? this.value : '');
          editor.isReadOnly = this.readOnly; //设置编辑器
          if (!this.readOnly) {
            //工具栏
            const toolbarContainer = document.querySelector(
              "#" + this.toolbarId
            );
            toolbarContainer.appendChild(editor.ui.view.toolbar.element);
            //编辑器内容变化监听
            editor.model.document.on("change:data", () => {
              // 编辑器内容发生变化时，告知外部，实现 v-model 双向监听效果
              this.$emit("input", editor.getData());
            });
            // 加载了适配器
            editor.plugins.get("FileRepository").createUploadAdapter = (
              loader
            ) => {
              return new UploadAdapter(loader);
            };
          }
          this.editor = editor; //将编辑器保存起来，用来随时获取编辑器中的内容等，执行一些操作
        })
        .catch((error) => {
          console.error(error);
        });
    },
  },
};
</script>
<style>
.ck-editor__editable_inline {
  height: 450px !important;
}
</style>